package com.kuyun.base.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kuyun.base.base.BaseController;
import com.kuyun.base.base.Page;
import com.kuyun.base.exception.KunYunException;
import com.kuyun.base.model.BaseDictionary;
import com.kuyun.base.model.BasePrivilege;
import com.kuyun.base.model.HttpResult;
import com.kuyun.base.model.ValidFormResult;
import com.kuyun.base.model.ZtreeBean;
import com.kuyun.base.service.BasePrivilegeService;
import com.kuyun.base.util.Constants;
import com.kuyun.base.util.IDUtil;

/**
 * 权限管理controller
 * 
 * @author 唐靖
 *
 * @date 2016年6月18日下午4:39:07
 *
 */
@Controller
@RequestMapping("/webback/BasePrivilege")
public class BasePrivilegeController extends BaseController {

	/**
	 * 跳转到权限列表页面
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月18日下午7:27:37
	 *
	 * @return
	 */
	@RequiresPermissions("PRIVILEGE_LIST")
	@RequestMapping("/toPrililegeListUI.do")
	public String toPrililegeListUI() {
		return "privilege/privilege_list";

	}

	/**
	 * 获取权限列表树
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年7月3日下午10:45:02
	 *
	 * @return
	 */
	@RequiresPermissions("PRIVILEGE_LIST")
	@RequestMapping(value = "/getPrivilegeTree.do", method = RequestMethod.POST)
	@ResponseBody
	public HttpResult getPrivilegeTree() {
		HttpResult result = new HttpResult();
		try {
			List<ZtreeBean> ps = basePrivilegeService.getPrivilegeTree();
			// 到这就是ok
			result.setObj(ps);
			result.setResultCode(Constants.RESULT_SUCCESS); // 操作成功
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 根据父权限id获取子权限列表
	 */
	@RequiresPermissions("PRIVILEGE_LIST")
	@ResponseBody
	@RequestMapping(value = "/getChildrenPrivilege.do")
	public Page<BasePrivilege> getChildrenPrivilege(String parentId, Page<BasePrivilege> page) {
		page = basePrivilegeService.findPrivilegeByParentId(parentId, page);
		return page;

	}

	/**
	 * 跳转到新增页面
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月18日下午7:27:37
	 *
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("PRIVILEGE_ADD")
	@RequestMapping("/toPrililegeAddUI.do")
	public String toPrililegeAddUI(String parentId, String level, Model model) throws Exception { // 父亲的id
		BasePrivilege base = null; // 父权限
		BaseDictionary typeDic = null;
		// BasePrivilege newPri = new BasePrivilege(); //
		// 要新增的权限,系统采用两级菜单，有些东西会在这里写死
		if ("root".equals(parentId) && "0".equals(level)) { // 要添加一级菜单
			base = new BasePrivilege();
			base.setId("0");
			base.setBasePrivilegeName("系统");
			typeDic = baseDictionaryService.findByCode(Constants.DIC_PRIVILEGE_TYPE_MENU);
			// 顶级菜单下边一定是菜单
		} else {
			base = basePrivilegeService.findSimplePrivilegeById(parentId); // 根据ID查询权限
			if ("2".equals(level)) { // 二级菜单，下边一定是操作
				// 二级菜单下边一定是操作权限
				typeDic = baseDictionaryService.findByCode(Constants.DIC_PRIVILEGE_TYPE_OPT);

			} else if ("1".equals(level)) { // 一级菜单，下边一定是二级菜单
				typeDic = baseDictionaryService.findByCode(Constants.DIC_PRIVILEGE_TYPE_MENU);
			}

		}
		model.addAttribute("base", base);
		model.addAttribute("typeDic", typeDic);
		return "privilege/privilege_edit";

	}

	/**
	 * 添加权限时的名称校验
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月25日下午6:38:50
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkPrivilegeName.do", method = RequestMethod.POST)
	public ValidFormResult checkPrivilegeName(String param, String id) {
		ValidFormResult v = new ValidFormResult();
		BasePrivilege p = new BasePrivilege();
		p.setBasePrivilegeName(param);
		p.setId(id);
		try {
			if (basePrivilegeService.checkName(p)) {
				v.setStatus(ValidFormResult.Y);
			} else {
				v.setInfo("该名称在系统中已存在");
			}
		} catch (Exception e) {
			v.setInfo("该名称在系统中已存在");
			e.printStackTrace();
		}
		return v;
	}

	/**
	 * 添加权限时的code校验
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月25日下午6:38:50
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkPrivilegeCode.do", method = RequestMethod.POST)
	public ValidFormResult checkPrivilegeCode(String param, String id) {
		ValidFormResult result = new ValidFormResult();
		BasePrivilege base = new BasePrivilege();
		base.setBasePrivilegeCode(param);
		base.setId(id);
		try {
			if (basePrivilegeService.checkCode(base)) {
				result.setStatus(ValidFormResult.Y);
			} else {
				result.setInfo("该编码已经存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setInfo("系统错误，请稍后再试");
		}
		return result;

	}

	/**
	 * 具体增加权限操作
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月19日下午1:40:50
	 *
	 * @return
	 */
	@RequiresPermissions("PRIVILEGE_ADD")
	@RequestMapping(value = "/toAddPrivilege.do", method = RequestMethod.POST)
	@ResponseBody
	public ValidFormResult toAddPrivilege(BasePrivilege basePrivilege, HttpServletRequest request) {
		ValidFormResult result = new ValidFormResult();
		if (!StringUtils.isEmpty(basePrivilege.getBasePrivilegeCode())
				&& !StringUtils.isEmpty(basePrivilege.getBasePrivilegeName())
				&& !StringUtils.isEmpty(basePrivilege.getBasePrivilegeType())) {
			basePrivilege.setId(IDUtil.getId());
			basePrivilege.setCreateTime(new Date());
			try {
				basePrivilegeService.createPrivilege(basePrivilege);
				updateSystemPrivilegeInfo(request);
				result.setStatus(ValidFormResult.Y);
			} catch (Exception e) {
				e.printStackTrace();
				if (e instanceof KunYunException) {
					result.setInfo(e.getMessage());
				}
			} // 添加权限
		} else {
			result.setInfo("数据操作不合法");
		}
		return result;

	}

	/**
	 * 跳转到修改页面
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月18日下午7:27:37
	 *
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("PRIVILEGE_UPDATE")
	@RequestMapping("/toPrililegeUpdateUI.do")
	public String toPrililegeUpdateUI(BasePrivilege basePrivilege, Model model) throws Exception {
		if (null == basePrivilege.getId()) {
			throw new KunYunException("非法请求");
		}
		basePrivilege = basePrivilegeService.findSimplePrivilegeById(basePrivilege.getId());
		BasePrivilege base = null;
		if (null == basePrivilege.getBaseParivilegeParentId()) {
			base = new BasePrivilege();
			base.setId("root");
			base.setBasePrivilegeName("系统");
		} else {
			base = basePrivilegeService.findSimplePrivilegeById(basePrivilege.getBaseParivilegeParentId()); // 父权限
		}
		BaseDictionary typeDic = baseDictionaryService.findByCode(basePrivilege.getBasePrivilegeType());

		model.addAttribute("basePrivilege", basePrivilege);
		model.addAttribute("base", base);
		model.addAttribute("typeDic", typeDic);
		return "privilege/privilege_edit";

	}

	/**
	 * 具体的更新操作
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年6月19日下午1:41:47
	 *
	 * @return
	 */
	@RequiresPermissions("PRIVILEGE_UPDATE")
	@ResponseBody
	@RequestMapping("/toUpdatePrivilege.do")
	public ValidFormResult toUpdatePrivilege(BasePrivilege basePrivilege, HttpServletRequest request) {
		ValidFormResult result = new ValidFormResult();
		if (!StringUtils.isEmpty(basePrivilege.getId()) && !StringUtils.isEmpty(basePrivilege.getBasePrivilegeCode())
				&& !StringUtils.isEmpty(basePrivilege.getBasePrivilegeName())
				&& !StringUtils.isEmpty(basePrivilege.getBasePrivilegeType())) {
			basePrivilege.setUpdateTime(new Date());
			try {
				basePrivilegeService.updatePrivilege(basePrivilege);
				updateSystemPrivilegeInfo(request);
				result.setStatus(ValidFormResult.Y);
			} catch (Exception e) {
				e.printStackTrace();
				if (e instanceof KunYunException) {
					result.setInfo(e.getMessage());
				}
			} // 添加权限
		} else {
			result.setInfo("数据操作不合法");
		}
		return result;

	}

	/**
	 * 修改权限状态
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年7月5日下午10:04:51
	 *
	 * @return
	 */
	@RequiresPermissions("PRIVILEGE_UPDATE")
	@RequestMapping("/changePrivageStatus.do")
	@ResponseBody
	public HttpResult changePrivageStatus(String id, String status, HttpServletRequest request) {
		HttpResult result = new HttpResult();
		try {
			BasePrivilege pri = basePrivilegeService.findSimplePrivilegeById(id);
			if (null != pri) {
				pri.setBasePrivilegeStatus(status);
				basePrivilegeService.updatePrivilege(pri);
				updateSystemPrivilegeInfo(request);
				result.setResultCode(Constants.RESULT_SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;

	}

	/**
	 * 重置系统权限
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年7月6日上午11:09:30
	 *
	 * @param request
	 */
	private void updateSystemPrivilegeInfo(HttpServletRequest request) {
		List<BasePrivilegeService> allMenu = basePrivilegeService.loadAllMenuPri(); // 加载出当前系统的所有菜单权限(级联好的)
		request.getServletContext().removeAttribute(Constants.APP_MENU_KEY);
		request.getServletContext().setAttribute(Constants.APP_MENU_KEY, allMenu); // 所有的菜单
	}

}
